<template>
	<view>
		
	
	<view style="flex: 1;width: 100%;overflow-y: scroll;">

		<scroll-view scroll-y="true" style="height: 97vh;padding-bottom: 30rpx;"
		:scroll-into-view="scrollView" :refresher-enabled="!isCompleted"
		@refresherrefresh="refresh" :scroll-top="scrollTop" :refresher-triggered="triggered" :scroll-with-animation="scroll_animation">
		<view id="message-scroll" style="height: 100%;" >
			<view style="text-align: center;font-size: 26rpx;color: #666;padding-top: 10rpx;" v-if="isCompleted">没有更多啦</view>
			<view v-for="(item,index) in list" :id="'a'+item.id" :key='index' style="margin-bottom: 30rpx;">
				<view v-if="item.type=='showTime'" style="line-height: 80rpx;text-align: center;color: #999999;font-size: 28rpx;">
					 {{ item.payload.text}}
				</view>
				<view v-if="item.right==2">
					<view style="overflow: hidden;width: 96%;margin: 0 auto;">
						<view style="width: 15%;float: left;overflow: hidden;">
							<image :src="item.client.avatar" style="width:80rpx;height: 80rpx;display: block;border-radius: 50%;float: left;" mode=""></image>
						</view>
						<view class="" style="max-width: 80%;float: left;overflow: hidden;">
							<!-- <view style="line-height: 40rpx;color: #333333;font-size: 28rpx;margin-bottom: 20rpx;">
								金煌
							</view> -->
							<view v-if="item.content_type=='TIMTextElem'" style="line-height: 50rpx;background-color: #1FB0AC;box-sizing: border-box;padding:10rpx 20rpx;border-radius: 2px 6px 6px 6px;color: #ffffff;font-size: 28rpx;">
								<text>{{item.content}}</text>
							</view>
							<view style="width: 150rpx;height: 200rpx;overflow: hidden;position: relative;border-radius: 10px 10px 10px 10px;" v-if="item.content_type=='TIMImageElem'">
								<image :src="item.content" style="width: 100%;position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);border-radius: 10px 10px 10px 10px;" mode="widthFix"></image>
							</view>
						</view>
					</view>
				</view>
				<view v-if="item.right==1">
					<view style="overflow: hidden;width: 96%;margin: 0 auto;">
						<view style="width: 16%;float: right;overflow: hidden;">
							<image :src="item.client.avatar" style="width:80rpx;height: 80rpx;display: block;border-radius: 50%;float: right;" mode=""></image>
						</view>
						<view class="" style="max-width: 80%;float: right;overflow: hidden;">
							<!-- <view style="line-height: 40rpx;color: #333333;font-size: 28rpx;margin-bottom: 20rpx;">
								金煌
							</view> -->
							<view v-if="item.content_type=='TIMTextElem'" style="line-height: 50rpx;background-color: #1FB0AC;box-sizing: border-box;padding:10rpx 20rpx;border-radius: 6px 2px 6px 6px;color: #ffffff;font-size: 28rpx;">
								<text>{{item.content}}</text>
							</view>
							<view style="width: 150rpx;height: 200rpx;overflow: hidden;position: relative;border-radius: 10px 10px 10px 10px;" v-if="item.content_type=='TIMImageElem'">
								<image :src="item.content" style="width: 100%;position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);border-radius: 10px 10px 10px 10px;" mode="widthFix"></image>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
			
		</scroll-view>
		<!-- <view style="width: 92%;height: 80rpx;position: fixed;left: 4%;bottom: 20rpx;overflow: hidden;padding-bottom: 30rpx;">
			<input v-model="msg" placeholder="请输入您要发送的内容" type="text"   style="width: 74%;float: left;background-color: #FFFFFF;height: 80rpx;line-height: 80rpx;border-radius: 40rpx;box-sizing: border-box;padding: 0 20rpx;color: #333333;font-size: 28rpx;" />
			<view @click="fasong" style="width: 22%;float: right;height: 80rpx;line-height: 80rpx;background-color: #0078FF;font-size:26rpx;text-align: center;border-radius: 40rpx;color: #FFFFFF;">
				发送
			</view>
		
		</view> -->
	</view>
	</view>
</template>

<script>
	export default{
		data(){
			return{
				roomid:'',
				company:'',
				page:1,
				list:[],
				enmpy:false,
				kk:false,
				msg:'',
				isCompleted: false, // 当前会话消息是否已经请求完毕
				triggered: false,
				Viewid:'',
				scrollView:'',
				scrollTop:0,
				shifou_gun:true,
				scroll_animation:true,
			}
		},
		onLoad(option) {
			// this.roomid=option.roomid
			// this.lts()
			this.page=1
			this.enmpy=false
			this.kk=false
			this.list=[]
			this.lt_list()
			
		},
		onShow() {
			
		},
		// onReachBottom: function() {
		// 	console.log(222222222)
		// 	if (this.enmpy) {
		// 		return
		// 	} else {
		// 		this.lt_list()
		// 	}
		// },
		methods:{
			// 聊天室详情
			lts:function(){
				this.post('api/chat/room_info',{chat_room_id:this.roomid},true).then(res=>{
					console.log(res)
					if(res.code==1){
						// uni.setNavigationBarTitle({
						// 	title: '聊天记录'
						// })
						this.company=res.data.user.firm_name
					}
				})
			},
			refresh() {
				let that=this
				if (this.isCompleted) {
					this.triggered=false
					return;
				}
				this.scroll_animation=false
				for(let i=0;i<this.list.length;i++){
					if(this.list[i].type!='showTime'){
						this.Viewid='a'+this.list[i].id
						break
					}
				}
				
				console.log(this.Viewid,11111)
				this.triggered=true
				this.lt_list()
				// this.scroll_animation = false;//关闭滑动动画
				// for(let i=0;i<this.messageList.length;i++){
				// 	if(this.messageList[i].type!="showTime"){
				// 		this.Viewid =this.messageList[i].ID;//记住第一个信息ID
				// 		break
				// 	}
				// }
				// console.log(this.Viewid,'loiuyuyhh')
				// this.triggered=true
				
				// setTimeout(() => {
				// 	this.setData({
				// 		triggered: false,
				// 	});
				// }, 2000);
			},
			lt_list:function(){
				let that=this
				let data={
					friend_id:uni.getStorageSync('friend_id'),
					user_id:uni.getStorageSync('user_id'),
					page:this.page,
					limit:10
				}
				if(!this.isCompleted){
					this.post('api/im/im/friend_message_list',data,true).then(res=>{
						if(res.code==1){
							this.triggered=false
							if(this.page==1){
								if (res.data.data== null || res.data.data.length == 0) {
									this.kk = true
									this.enmpy = true
									return
								} else if (res.data.data.length < 10) {
									this.enmpy = true
								}
							}else{
								if (res.data.data== null || res.data.data.length == 0) {
									this.enmpy = true
									return
								} else if (res.data.data.length < 10) {
									this.enmpy = true
								}
							}
							
							if(res.data.data.length<10){
								this.isCompleted=true
							}else{
								this.isCompleted=false
							}
							if(!this.shifou_gun){
								this.$nextTick(function() {
									that.scrollView = that.Viewid;//跳转上次的第一行信息位置
									
								});
								
							}
							if(!this.shifou_gun){
								this.$nextTick(function() {
									
									this.scroll_animation = true;//恢复滚动动画
									
								});
								
								
							}
							this.page++
							this.list = [...res.data.data.reverse(), ...this.list];
							this.list = this.msgTimeFormat(this.list,0,0)
							console.log(this.list,22222)
							if(this.shifou_gun){
								setTimeout(function(){
									that.scrollToButtom()
									
								},100)
								that.shifou_gun=false
							}
						}else{
							this.kk = true
							uni.showToast({
								title: res.msg,
								icon: "none",
								duration: 1000
							})
						}
					})
				}else{
					this.triggered=false
				}
			},
			scrollToButtom() {
				const query = uni.createSelectorQuery().in(this);
				let nodesRef = query.select('#message-scroll');
				nodesRef
					.boundingClientRect(res => {
						console.log(res,'liuuuuuuuu')
						// uni.pageScrollTo({
						// 　　　　duration:2000,
						// 　　　　scrollTop:res.height
						// 　})
						this.$nextTick(() => {
							//进入页面滚动到底部
							this.scrollTop = res.height;
							uni.setStorageSync('gaodu',res.height)
							console.log(this.scrollTop,123456789)
						});
					})
					.exec();
					
				
			},
			
			_formatDate : function (date, fmt) {
			        var o = {
			                "M+": date.getMonth() + 1, //月份
			                "d+": date.getDate(), //日
			                "h+": date.getHours(), //小时
			                "m+": date.getMinutes(), //分
			                "s+": date.getSeconds(), //秒
			                "q+": Math.floor((date.getMonth() + 3) / 3), //季度
			                "S": date.getMilliseconds() //毫秒
			        };
			        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
			        for (var k in o)
			                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			                        return fmt;
			},
			_getTimeStringAutoShort2 (timestamp, mustIncludeTime){
			 
			        // 当前时间
			        var currentDate = new Date();
			        // 目标判断时间
			        var srcDate = new Date(parseInt(timestamp));
			 
			        var currentYear = currentDate.getFullYear();
			        var currentMonth = (currentDate.getMonth()+1);
			        var currentDateD = currentDate.getDate();
			 
			        var srcYear = srcDate.getFullYear();
			        var srcMonth = (srcDate.getMonth()+1);
			        var srcDateD = srcDate.getDate();
			 
			        var ret = "";
			 
			        // 要额外显示的时间分钟
			        var timeExtraStr = (mustIncludeTime?" "+this._formatDate(srcDate, "hh:mm"):"");
			 
			        // 当年
			        if(currentYear == srcYear) {
			                var currentTimestamp = currentDate.getTime();
			                var srcTimestamp = timestamp;
			                // 相差时间（单位：毫秒）
			                var deltaTime = (currentTimestamp-srcTimestamp);
			 
			                // 当天（月份和日期一致才是）
			                if(currentMonth == srcMonth && currentDateD == srcDateD) {
			                // 时间相差60秒以内
			                if(deltaTime < 60 * 1000)
			                        ret = "刚刚";
			                // 否则当天其它时间段的，直接显示“时:分”的形式
			                else
			                        ret = this._formatDate(srcDate, "hh:mm");
			                }
			                // 当年 && 当天之外的时间（即昨天及以前的时间）
			                else {
			                        // 昨天（以“现在”的时候为基准-1天）
			                        var yesterdayDate = new Date();
			                        yesterdayDate.setDate(yesterdayDate.getDate()-1);
			 
			                        // 前天（以“现在”的时候为基准-2天）
			                        var beforeYesterdayDate = new Date();
			                        beforeYesterdayDate.setDate(beforeYesterdayDate.getDate()-2);
			 
			                        // 用目标日期的“月”和“天”跟上方计算出来的“昨天”进行比较，是最为准确的（如果用时间戳差值
			                        // 的形式，是不准确的，比如：现在时刻是2019年02月22日1:00、而srcDate是2019年02月21日23:00，
			                        // 这两者间只相差2小时，直接用“deltaTime/(3600 * 1000)” > 24小时来判断是否昨天，就完全是扯蛋的逻辑了）
			                        if(srcMonth == (yesterdayDate.getMonth()+1) && srcDateD == yesterdayDate.getDate())
			                                ret = "昨天"+timeExtraStr;// -1d
			                        // “前天”判断逻辑同上
			                        else if(srcMonth == (beforeYesterdayDate.getMonth()+1) && srcDateD == beforeYesterdayDate.getDate())
			                                ret = "前天"+timeExtraStr;// -2d
			                        else{
			                                // 跟当前时间相差的小时数
			                                var deltaHour = (deltaTime/(3600 * 1000));
			 
			                                // 如果小于或等 7*24小时就显示星期几
			                                if (deltaHour <= 7*24){
			                                var weekday=new Array(7);
			                                weekday[0]="星期日";
			                                weekday[1]="星期一";
			                                weekday[2]="星期二";
			                                weekday[3]="星期三";
			                                weekday[4]="星期四";
			                                weekday[5]="星期五";
			                                weekday[6]="星期六";
			 
			                                // 取出当前是星期几
			                                var weedayDesc = weekday[srcDate.getDay()];
			                                ret = weedayDesc+timeExtraStr;
			                                }
			                                // 否则直接显示完整日期时间
			                                else
			                                ret = this._formatDate(srcDate, "yyyy/M/d")+timeExtraStr;
			                        }
			                }
			        }
			        // 往年
			        else{
			                ret = this._formatDate(srcDate, "yyyy/M/d")+timeExtraStr;
			        }
			 
			        return ret;
			},
			msgTimeFormat(currentMessageList, sort, type) {
			    // console.log('传入的会话数组', currentMessageList)
			    const newMessageList = []
			    const currentFilterList = currentMessageList.filter((item) => {
			        return item.type !== 'showTime'
			    })
			    currentFilterList.forEach((item, index) => {
			        const date = item.time * 1000
			        let showTime
			        if (index === 0) {
			        //第一条必显示时间
			            showTime = this._getTimeStringAutoShort2(date, true)
			            newMessageList.push({
			                payload: {
			                    text: showTime
			                },
			                type: 'showTime',//超五分钟显示时间-标识
			                time: item.time
			            })
			            newMessageList.push(item)
			        } else if (index <= currentFilterList.length - 1) {
			            const current = currentFilterList[index].time
			            let minutes
			            const showTimeList = newMessageList.filter((item) => {
			                return item.type === 'showTime'
			            })
			            const lastShowTime = showTimeList[showTimeList.length - 1].time//添加的时间且最后一条，用于对比
			            if (type) {
			                const prev = currentFilterList[index - 1].time
			                minutes = (current - prev) / 60
			            }
			            if (!sort) {
			                minutes = (current - lastShowTime) / 60
			            } else {
			                minutes = (lastShowTime - current) / 60
			            }
			            //超五分
			            if (minutes > 5) {
			                showTime = this._getTimeStringAutoShort2(date,  true)
			                newMessageList.push({
			                    payload: {
			                        text: showTime
			                    },
			                    type: 'showTime',
			                    time: item.time
			                })
			                newMessageList.push(item)
			            } else {
			                newMessageList.push(item)
			            }
			        }
			    })
			    // console.log('最后得到的数组', newMessageList)
			    return newMessageList
			},
			
			
		}
	}
</script>

<style lang="scss">
	page{
		background-color: #F8F8F8!important;
		font-family: Demibold;
		padding-bottom: 30rpx;
	}
</style>
